package com.mengshu.token.properties;

import com.mengshu.token.utils.TimeUtils;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.io.Serializable;
import java.util.LinkedHashMap;

/**
 * Token配置类
 */
@Setter
@Getter
@ConfigurationProperties(prefix = TokenProperties.PREFIX)
public class TokenProperties implements Serializable {
    private static final long serialVersionUID = 134809516851102975L;

    public static final String PREFIX = "mengshu.token";

    public final static String DEFAULT_TOKEN_KEY = "default";

    // 是否启用
    private boolean enable = true;
    // token存储前缀
    private String prefix = "mengshu-token";
    // 排除指定路径
    private String excludes;
    // 登录失效时间 默认30分钟 例如 5s 五秒，6m 六分钟，7h 七小时，8d 八天
    private String timeout = "30m";
    // 登录失效时间 单位s
    @Getter
    private long longTimeout = TimeUtils.getSeconds(timeout);
    // 多token配置 multi存在时 下面的配置字段将失效
    private LinkedHashMap<String, TokenConfig> multi;

    public void setTimeout(String timeout) {
        this.timeout = timeout;
        this.longTimeout = TimeUtils.getSeconds(timeout);
    }

    public LinkedHashMap<String, TokenConfig> getMultiTokenConfig() {
        if (isMultiTokenConfig()) {
            return multi;
        }
        return new LinkedHashMap<String, TokenConfig>(){{
            put(DEFAULT_TOKEN_KEY, getDefaultTokenConfig());
        }};
    }

    public boolean isMultiTokenConfig() {
        return multi != null;
    }

    private TokenConfig getDefaultTokenConfig() {
        if (isMultiTokenConfig()) {
            return this.multi.values().iterator().next();
        }
        return new TokenConfig(this.prefix, this.excludes, this.timeout);
    }

}
